package com.ht.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ht.constant.BusConstant;
import com.ht.module.sys.entity.SysUser;
import com.ht.module.sys.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: ht
 * @ClassName: JwtUtils
 * @Author: hejialun
 * @Description: jwt工具类
 * @Date: 2021/5/25 11:50
 */

@Slf4j
@Component
public class JwtUtils {

    @Autowired
    private RedisUtil redis;
    @Autowired
    private static RedisUtil redisUtil;


    @PostConstruct
    public void init() {
        JwtUtils.redisUtil = redis;
    }


    //token密钥
    public static final String publicKey = "HT_BASE";

    public static String getUserToken(SysUser sysUser) {
        String jwtToken = JwtUtils.sign(getUserJwtMap(sysUser));
        return jwtToken;
    }

    /**
     * 通过用户信息生成用户的jwttoken
     * @param sysUser
     * @return
     */
    public static Map<String, Object> getUserJwtMap(SysUser sysUser) {
        //吧用户信息存到token里面
        Map<String, Object> jwtMap=new HashMap<>();
        jwtMap.put(BusConstant.JWTUserId, sysUser.getId());                 //设置用户id
        jwtMap.put(BusConstant.JWTDeptId, sysUser.getDeptId());             //设置部门id
        jwtMap.put(BusConstant.JWTUserNmae, sysUser.getUsername());         //设置用户名
        return jwtMap;
    }

    /**
     * 校验token是否正确
     *
     * @param token 密钥
     * @return 是否正确
     */
    public static boolean verify(String token, String username) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(publicKey);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", username)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @param token
     * @param key
     * @return
     */
    public static String getKey(String token, String key) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(key).asString();
        } catch (JWTDecodeException e) {
            log.error("error：{}", e.getMessage());
            return null;
        }
    }

    /**
     * 生成签名
     *
     * @param map
     * @return 加密的token
     */
    public static String sign(Map<String, Object> map) {
        Algorithm algorithm = Algorithm.HMAC256(publicKey);
        JWTCreator.Builder builder = JWT.create();
        for (String key : map.keySet()) {
            builder.withClaim(key, map.get(key)+"")
                    .withClaim("createTime", DateUtil.getTime())
                    .withClaim("random", Math.random() * 1000);
        }
        String token = builder.sign(algorithm);
        return token;
    }


}